package com.wdl.modules.myhouse.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wdl.modules.myhouse.dao.FileTypeDao;
import com.wdl.modules.myhouse.dto.FileTypeDTO;
import com.wdl.modules.myhouse.entity.FileTypeEntity;
import com.wdl.modules.myhouse.service.FileTypeService;
import com.wdl.modules.myhouse.common.Constant;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;


/**
 * @author lucain sunlightcs@gmail.com
 * @since 1.0.0 2022-08-13
 */
@Service
public class FileTypeServiceImpl extends ServiceImpl<FileTypeDao, FileTypeEntity> implements FileTypeService {


    @Override
    public List<FileTypeDTO> getAllRoot() {
        QueryWrapper<FileTypeEntity> wrapper = new QueryWrapper<>();
        wrapper.lambda().eq(FileTypeEntity::getParentTypeId, Constant.FILE_TYPE_ROOT_ID);
        List<FileTypeEntity> rootNodes = this.baseMapper.selectList(wrapper);
        List<FileTypeDTO> list = rootNodes.stream().map(rootNode -> {
            FileTypeDTO dto = new FileTypeDTO();
            BeanUtils.copyProperties(rootNode, dto);
            dto.setPath("/" + rootNode.getSourceTypeName());
            //填充子节点
            if (rootNode.getChildTypeId() != null) {
                String[] childNodes = rootNode.getChildTypeId().split(",");
                List<FileTypeDTO> childNodes1 = Arrays.stream(childNodes).map(node -> fillTheChild(Integer.valueOf(node))).collect(Collectors.toList());
                dto.setChildNodes(childNodes1);
            }
            return dto;
        }).collect(Collectors.toList());
        return list;
    }


    private FileTypeDTO fillTheChild(Integer nodeId) {
        FileTypeEntity entity = this.baseMapper.selectById(nodeId);
        String childNodes = entity.getChildTypeId();
        FileTypeDTO dto = new FileTypeDTO();
        if (childNodes != null && !childNodes.isEmpty()) {
            String[] nodes = childNodes.split(",");
            List<FileTypeDTO> childNodes1 = Arrays.stream(nodes).map(node -> {
                FileTypeDTO childNode = fillTheChild(Integer.valueOf(node));
                return childNode;
            }).collect(Collectors.toList());
            dto.setChildNodes(childNodes1);
        }
        BeanUtils.copyProperties(entity, dto);
        return dto;
    }


}